package cn.bonoon.kernel.util;

import java.lang.reflect.Method;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;

public final class ClassHelper {
	private ClassHelper() {
	}

	public final static Class<?> forName(String className) {
		if (StringHelper.isNotEmpty(className)) {
			try {
				return Class.forName(className);
			} catch (Throwable t) {
			}
		}
		return null;
	}

	public final static <T> T newInstance(Class<T> clazz, Class<?> c) {
		try {
			Object o = c.newInstance();
			clazz.cast(o);
		} catch (Throwable t) {

		}
		return null;
	}

	public final static <T> T newInstance(Class<T> clazz, String name) {
		if (StringHelper.isNotEmpty(name))
			try {
				Class<?> c = Class.forName(name);
				Object o = c.newInstance();
				clazz.cast(o);
			} catch (Throwable t) {
				//nothing to do
			}
		return null;
	}


	public final static Method findMethod(Class<?> objectClass, String methodName) {
		Method[] methods = objectClass.getDeclaredMethods();
		for (int i = 0; i < methods.length; i++) {
			Method method = methods[i];
			if (method.getParameterTypes().length == 1 && methodName.equals(method.getName()))
				return method;
		}
		return null;
	}
	
	@SuppressWarnings("unchecked")
	public final static <E> Class<E> getActualTypeArgument(Class<?> cls, Class<?> stop, int i){
		Class<?> c = cls;
		while(!stop.equals(c)){
			Type t = c.getGenericSuperclass();
			if(t instanceof ParameterizedType){
				ParameterizedType genericSuperclass = (ParameterizedType)t;
				return (Class<E>) genericSuperclass.getActualTypeArguments()[i];
			}
			c = c.getSuperclass();
		}
		return null;
	}
}
